package com.wang.yupao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.yupao.common.BaseResponse;
import com.wang.yupao.common.ErrorCode;
import com.wang.yupao.common.ResultUtils;
import com.wang.yupao.exception.BusinessException;
import com.wang.yupao.model.domain.Team;
import com.wang.yupao.model.domain.User;
import com.wang.yupao.model.domain.UserTeam;
import com.wang.yupao.model.dto.TeamGetQuery;
import com.wang.yupao.model.dto.TeamQuery;
import com.wang.yupao.model.request.*;
import com.wang.yupao.model.vo.TeamUserVO;
import com.wang.yupao.service.TeamService;
import com.wang.yupao.service.UserService;
import com.wang.yupao.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 队伍接口
 *
 * @author wang
 */
@RestController
@RequestMapping("/team")
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
@Slf4j
public class TeamController {

    @Resource
    private UserService userService;

    @Resource
    private TeamService teamService;

    @Resource
    private UserTeamService userTeamService;

    /**
     * 添加队伍（创建队伍）
     *
     * @param teamAddRequest
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        if (teamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        team.setHasJoinNum(1);
        long teamId = teamService.addTeam(team, loginUser);
        return ResultUtils.success(teamId);
    }


    /**
     * 逻辑删除队伍
     *
     * @param
     * @return
     */
//    @PostMapping("/delete")
//    public BaseResponse<Boolean> deleteTeam(@RequestParam("id") long id) {
//        if (id <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        boolean res = teamService.removeById(id);
//        if (!res) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "删除错误");
//        }
//
//        return ResultUtils.success(true);
//    }
    @GetMapping("/get")
    public BaseResponse<TeamGetQuery> getUpdateTeam(@RequestParam("id") long id, HttpServletRequest request) {
//        log.info("getUpdateTeam id: " + id);
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TeamGetQuery teamGetQuery = teamService.getUpdateTeamById(id);
        return ResultUtils.success(teamGetQuery);
    }

    /**
     * 更新队伍
     *
     * @param teamUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Long> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        if (teamUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean res = teamService.updateTeam(teamUpdateRequest, loginUser);
        if (!res) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "更新错误");
        }
        return ResultUtils.success(teamUpdateRequest.getId());
    }

    /**
     * 获取所有队伍信息
     *
     * @param teamQuery
     * @return
     */
//    @GetMapping("/list")
//    public BaseResponse<List<Team>> getListTeam(TeamQuery teamQuery) {
//        if (teamQuery == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        Team team = new Team();
//        BeanUtils.copyProperties(teamQuery, team);
//        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
//        List<Team> teamList = teamService.list(queryWrapper);
//        return ResultUtils.success(teamList);
//    }


    /**
     * 获取我创建的队伍
     *
     * @param request
     * @return
     */
    @GetMapping("/list/my/create")
    public BaseResponse<List<TeamUserVO>> getMyCreateListTeam(@RequestParam("searchText") String searchText, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        List<TeamUserVO> myCreateTeamList = teamService.getMyCreateTeam(loginUser, searchText);
        myCreateTeamList.forEach(team -> {
            team.setHasJoin(true);
        });
        return ResultUtils.success(myCreateTeamList);
    }

    /**
     * 获取我加入的队伍
     *
     * @param request
     * @return
     */
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVO>> getMyJoinListTeam(@RequestParam("searchText") String searchText, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        List<TeamUserVO> myJoinTeamList = teamService.getMyJoinTeam(loginUser, searchText);
        myJoinTeamList.forEach(team -> {
            team.setHasJoin(true);
        });
        return ResultUtils.success(myJoinTeamList);
    }

    /**
     * 根据用户添加查询列表
     *
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> getListTeam(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean isAdmin = userService.isAdmin(request);
        //所有队伍
        List<TeamUserVO> teamList = teamService.listTeam(teamQuery, isAdmin);
        //取出所有队伍的id
        List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).collect(Collectors.toList());
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();

        User loginUser = userService.getLoginUser(request);
        userTeamQueryWrapper.eq("userId", loginUser.getId());
        userTeamQueryWrapper.in("teamId", teamIdList);
        //取出当前用户已加入队伍的关系表集合
        List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
        //取出已加入队伍id集合
        Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
        //将已加入的队伍的hasJoin字段设置为true
        teamList.forEach(team -> {
            boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
            team.setHasJoin(hasJoin);
        });
        return ResultUtils.success(teamList);
    }

    /**
     * 分页获取队伍信息
     * todo hasJoin字段没有设置
     *
     * @param teamQuery
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<List<Team>> ListTeamsPages(TeamQuery teamQuery) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamQuery, team);
        Page<Team> page = new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize());
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        Page<Team> resultPage = teamService.page(page, queryWrapper);
        List<Team> teamPageList = resultPage.getRecords();
        return ResultUtils.success(teamPageList);
    }

    /**
     * 加入队伍
     *
     * @param teamJoinRequest
     * @param request
     * @return
     */
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.joinTeam(teamJoinRequest, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 退出队伍
     *
     * @param teamQuitRequest
     * @param request
     * @return
     */
    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        if (teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.quitTeam(teamQuitRequest, loginUser);
        return ResultUtils.success(result);
    }


    /**
     * 解散队伍
     *
     * @param teamDeleteRequest 队伍id
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody TeamDeleteRequest teamDeleteRequest, HttpServletRequest request) {
        long id = teamDeleteRequest.getId();
//        log.info("deleteTeam id: " + id);
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.deleteTeam(id, loginUser);
        return ResultUtils.success(result);
    }


}
